// index.js
// 获取应用实例
const app = getApp()
const { connect } = require('../../utils/mqtt')
 
const mqttHost = 'broker.emqx.io' //mqtt服务器域名地址
const mqttPort = 8084 //mqtt服务器的端口
const SubTopic = '/smart_home/sub' //设备消息订阅的主题(小程序消息发布的主题)
const PubTopic = '/smart_home/pub' //设备消息发布的主题(小程序消息订阅的主题)
const mpSubTopic = PubTopic
const mpPubTopic = SubTopic

Page({
  data: {
    client:null,
    Temp:0,
    Hum:0,
    Light:0,
    Led:false,
    Beep:false
  },

  //LED状态改变事件
  onLedChange(event){
    const that = this
    console.log(event.detail.value)
    that.setData({Led:event.detail.value})
    if(event.detail.value){
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"LED",
        value:1
      }),function(err){
        if(!err){
          console.log('成功下发指令-----开灯')
        }
      })
    }else{
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"LED",
        value:0
      }),function(err){
        if(!err){
          console.log('成功下发指令-----关灯')
        }
      })
    }
  },

  //Beep状态改变事件
  onBeepChange(event){
    const that = this
    console.log(event.detail.value)
    that.setData({Beep:event.detail.value})
    if(event.detail.value){
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"BEEP",
        value:1
      }),function(err){
        if(!err){
          console.log('成功下发指令-----打开报警器')
        }
      })
    }else{
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"BEEP",
        value:0
      }),function(err){
        if(!err){
          console.log('成功下发指令-----关闭报警器')
        }
      })
    }
  },

  // 事件处理函数 
  onShow(){
    const that = this
    that.setData({
      //wxs 实际上就是wss => wss 实际上就是SSL加密通信的websocket协议
       client: connect(`wxs://${mqttHost}:${mqttPort}/mqtt`)
    })
    that.data.client.on('connect',function(params){
      console.log('成功连接到MQTT服务器')
      wx.showToast({
        title: '连接成功',
        icon:'success',
        mask: true
      })
      that.data.client.subscribe(mpSubTopic,function(err){
        if(!err){
          console.log("成功订阅设备上行数据Topic!")
        }
      })
    })
    that.data.client.on('message',function(topic,message){
      console.log(topic)
      console.log(message)
      // message 是 16进制的buffer字节流

      let dataFromDev = {}
      try {
        dataFromDev = JSON.parse(message)
        console.log(dataFromDev)
        that.setData({
          Temp:dataFromDev.Temp,
          Hum:dataFromDev.Hum,
          Light:dataFromDev.Light,
          Led:dataFromDev.Led,
          Beep:dataFromDev.Beep
        })
      } catch (error) {
        console.log('JSON解析失败',error)
      }
    })
  },
})
